package com.xsir.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xsir.dto.CommentList;
import com.xsir.entity.Comment;
import com.xsir.entity.Reply;
import com.xsir.mapper.CommentMapper;
import com.xsir.mapper.ReplyMapper;
import com.xsir.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author xsir
 * @since 2020-11-08
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private ReplyMapper replyMapper;
    
    @Override
    public List<CommentList> getArticleComment(Page<Comment> page, Long articleId) {
        List<CommentList> commentList = new ArrayList<>();
        // 1、获取文章的所有评论
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<Comment>().eq("article_id", articleId)
                                                                        .eq("status", 0)
                                                                        .orderByDesc("create_time");;
        Page<Comment> commentPage = commentMapper.selectPage(page, queryWrapper);
        List<Comment> comments = commentPage.getRecords();
        if(comments.isEmpty()) {
            return null;
        }
        // 2、获取评论的所有回复
        comments.forEach(c -> {
            List<Reply> replies = replyMapper.selectList(new QueryWrapper<Reply>().eq("comment_id", c.getId()));
            CommentList tmpList = new CommentList(c);
            tmpList.setReplies(replies);
            commentList.add(tmpList);
        });
        
        return commentList;
    }
}
